package com.pinoc.demo.config.zk;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

/**
 * @author yinpeng
 */
public class ZookeeperCreateNode implements Watcher {

	public static CountDownLatch count = new CountDownLatch(1);

	public static void main(String[] args) {
		try {
			ZooKeeper zooKeeper = new ZooKeeper(ZKConstants.ZK_ADDRESS, 5000, new ZookeeperCreateNode());
			count.await();
			//临时节点 临时节点的过期时间与客户端会话保持一致
			String path = zooKeeper.create("/Locks/demo/name-", "yinpeng".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
			//临时顺序节点
			System.out.println("创建节点成功，" + path);
			String path1 = zooKeeper.create("/Locks/demo/name-", "yinpeng".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
			System.out.println("创建节点成功，" + path1);
			Thread.sleep(10000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void process(WatchedEvent watchedEvent) {
		if(watchedEvent.getState() == KeeperState.SyncConnected) {
			count.countDown();
		}
	}
}
